<?php

namespace App\Admin\Utils;

use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Lib\WeApp\WeApp;
use App\Models\Mp\WxMpFreePublish;
use App\Models\Posts\WxPost;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;

class MpUtils{
    private static $mpSrrvier;

    public static function generate_a_push($the_number, $posts, $bg_url = '', $head_html = '', $tail_html = ''){
        if(_empty_($posts)){
            return null;
        }

        if(_empty_(self::$mpSrrvier)){
            $weapp = new WeApp('mp');
            self::$mpSrrvier = $weapp->getMpServicer();
        }


        $last_html = '<section style="visibility: visible; margin-bottom: 0px;"><section style="background-image: url(&quot;'.($bg_url ?: Settings::get('app_mp_free_publish_default_bg_mp', env('APP_URL', 'https://mini.minisns.cn').'/statics/images/Mp/640.png')).'&quot;); background-size: contain; background-attachment: fixed; padding-top: 6px; font-size: 0px; visibility: visible;">';
        if($head_html){
            $last_html .= $head_html;
        }else{

        }
        $is_wxlink = Settings::get('app_mp_free_publish_is_wxurl', 0) == 1;

        $posts_title = '';
        foreach ($posts as $tmp_post_id){
            $first_post = WxPost::find($tmp_post_id);
            $posts_content_raw = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$first_post->posts_content );
            $posts_content_raw = trim_all_space(strip_tags( html_entity_decode(_mini_phone(_mini_aite_replace(_mini_emoji($posts_content_raw, true), true), true)), ['<br>']), true, true);
            $posts_title = PostUtils::get_the_title($posts_content_raw, $first_post->id, 25);
            if(mb_strlen($posts_title) >= 14){
                break;
            }
        }


        foreach ($posts as $post_id){
            $last_html .= self::post_embed($post_id, $is_wxlink);
        }
        if($tail_html){
            $last_html .= $tail_html;
        }else{
            $last_html .= Settings::get('app_mp_free_publish_tail', '<section style="background: rgba(0, 0, 0, 0.4);padding: 4px;text-align: center;color: rgba(255, 255, 255, 0.8);font-size: 12px;">以上内容由用户发布，不代表本公众号立场</section>');
        }
        $last_html .= '</section></section>';

        $publish_title = Settings::get('app_mp_free_publish_title', '墙墙第【the_id】期，【first_title】...');
        $publish_title = str_replace( ['【the_number】','【first_title】'], [$the_number,$posts_title], $publish_title);

        $free_publish = new WxMpFreePublish();
        $free_publish->title =  StrUtils::limit($publish_title, 30);
        $free_publish->author = Settings::get('app_mp_free_publish_author', '');
        $free_publish->digest = '';
        $free_publish->content = $last_html;
        $free_publish->content_source_url = Settings::get('app_h5_home', '');
        $free_publish->thumb_url = Settings::get('app_mp_free_publish_thumb_url','https://img.mini.minisns.cn/2023/05/22/17f31da7ce65a148b7c879c066f56f71.png');
        $free_publish->need_open_comment = Settings::get('app_mp_free_publish_need_open_comment', 1);
        $free_publish->only_fans_can_comment = Settings::get('app_mp_free_publish_only_fans_can_comment', 0);
        $r = $free_publish->save();
        if($r){
            return $free_publish->id;
        }
        return null;
    }

    private static function post_embed($post_id, $is_wxlink = false){
        $post = WxPost::find($post_id);
        if(!$post){
            return '';
        }
        global $__MINI_GLOBAL_REQUEST_ENV__;
        if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
            $__MINI_GLOBAL_REQUEST_ENV__ = 'console';
        }
        $author = UserUtils::get_cached_user($post->user_id);
        $comment_count = WxCommentRepositores::commentCount($post->id);//评论数量

        $format_time = format_datetime($post->created_at);
        PostUtils::mediaProcess($post, 0, 9009);
        $img_str = '';

        $h5_url = Settings::get('app_h5_home', '').'/#/pages/sticky/sticky?id='.$post->id . '&tenant=' . $post->tenant_id;
        $short_link = '';
        if($is_wxlink){
            $mini_app = new WeApp();
            $wxlink = $mini_app->getWxLink();
            try {
                $h5_url = $wxlink->genWxUrllink('pages/sticky/sticky', 'id='.$post->id.'&fph=1&tenant='. $post->tenant_id);
                $short_link = $wxlink->genWxShortlink('pages/sticky/sticky?id='.$post->id.'&fph=1'.'&tenant=' . $post->tenant_id, ($post->posts_title ?: '' ), false);
            }catch (\Exception $e){
                $h5_url = Settings::get('app_h5_home', '').'/#/pages/sticky/sticky?id='.$post->id . '&tenant=' . $post->tenant_id;
            }
        }

        if($post->images && count($post->images) > 0){
            $img_add_num = 0;
            for ($i = 0; $i < count($post->images); $i++){
                if($img_add_num >= 3){
                    break;
                }
                if(strpos($post->images[$i]['img_url'], '?imageMogr2') !== false){
                    $the_img_url = explode('?imageMogr2', $post->images[$i]['img_url'])[0];
                }else{
                    $the_img_url = $post->images[$i]['img_url'];
                }
                $res = self::$mpSrrvier->uploadMediaImg($the_img_url);
                // 将 mp-src 属性的值设置为 src 属性的值
                if($res['code'] == 200){
                    $img_str .= '<section style="width: 100%; padding-bottom: 100%; border-radius: 6px; object-fit: cover; background-image: url(&quot;'.$res['url'].'&quot;); background-size: cover; background-repeat: no-repeat; background-position: center center; font-size: 0px;" mp-bg-src="">
                        <br>
                    </section>';
                    $img_add_num++;
                }
            }
            $img_str = '<a href="'.$h5_url.'" data-linktype="2"><section style="display: grid;grid-template-columns: repeat(3, 1fr);gap: 6px;margin-top: 10px;margin-left: 2em;">'.$img_str.'</section></a>';
        }


        $content_str = '';
        if($post->posts_title){
            $content_str .= '<section>'.$post->posts_title.'</section>';
        }

        if($post->posts_content_raw){
            if(strpos($post->posts_content_raw, '<br>') !== false){
                $posts_content_raw_arr = explode('<br>', $post->posts_content_raw);
                if(isset($posts_content_raw_arr[0])){
                    $content_str .= '<section>'.$posts_content_raw_arr[0].'</section>';
                }
                if(isset($posts_content_raw_arr[1])){
                    if(isset($posts_content_raw_arr[2])){
                        $content_str .= '<section>'.$posts_content_raw_arr[1].'...</section>';
                    }else{
                        $content_str .= '<section>'.$posts_content_raw_arr[1].'</section>';
                    }
                }
            }else{
                $content_str .= '<section>'.$post->posts_content_raw.'</section>';
            }
        }

        $a_ = '<a href="'.$h5_url.'"
					style="color: currentcolor;" data-linktype="2">
						共'.$comment_count.'条评论，点击查看评论、回复作者→
					</a>';
        if($is_wxlink && $short_link){
            $a_ = '<a class="weapp_text_link js_weapp_entry wx_tap_link js_wx_tap_highlight" style="font-size:12px;" data-miniprogram-appid="'.Settings::get('app_id', '').'" data-miniprogram-path="pages/sticky/sticky?id='.$post->id.'" data-miniprogram-applink="'.$short_link.'" data-miniprogram-nickname="'.Settings::get('app_title', '').'" href="" data-miniprogram-type="text" data-miniprogram-servicetype="">共'.$comment_count.'条评论，点击查看评论、回复作者→</a>';
        }



        return '
        <section style="display: inline-block;overflow-x: auto;margin-bottom: 8px;width: 100% !important;">
	<section style="overflow: hidden;width: 100%;display: flex;-webkit-box-align: center;align-items: center;">
		<section style="width: 100%;padding-right: 6px;padding-left: 6px;">
			<section style="background: '.Settings::get('app_mp_free_publish_post_bg_color', 'rgba(108,130,250,0.5)').';border-radius: 4px;padding: 10px;">
				<section style="display: flex;-webkit-box-align: center;align-items: center;-webkit-box-pack: justify;justify-content: space-between;line-height: 1;">
					<section style="font-size: 12px;color: rgb(51, 51, 51);display: flex;-webkit-box-align: center;align-items: center;">
						<img src="'.$author['user_avatar'].'" data-type="jpeg" data-w="300" style="margin-right: 4px; width: 14px !important; height: auto !important; border-radius: 100px; object-fit: cover; visibility: visible !important;">
						'.$author['user_name'].'
					</section>
					<section style="font-size: 12px;color: rgb(51, 51, 51);">
						'.$format_time.'
					</section>
				</section>
				<section style="font-size: 16px;margin-top: 10px;">
					<section style="color: rgb(255, 255, 255);text-indent: 2em;">
						<a href="'.$h5_url.'" style="color: currentcolor;" data-linktype="2">
							<section>'.$content_str.'</section>
						</a>
					</section>
					'.$img_str.'
				</section>
				<section style="text-align: right;font-size: 12px;margin-top: 10px;color: rgb(51, 51, 51);">
					'.$a_.'
				</section>
			</section>
		</section>
	</section>
</section>
        ';
    }
}
